let { User } = require('../model/index')
let fn_user = async (ctx, next) => {
    let list_user = await User.findAll({
        order:['id']
    })
    ctx.body = list_user
}

let fn_cha = async (ctx, next) => {
    let word = ctx.request.params.word
    let list = await User.findAll()
    let lists = list.filter(item => {
        if (item.id == word || item.biaoti == word || item.zhaiyao == word || item.zuozhe == word || item.fenlei == word || item.neirong == word) {
            return item
        }
    })
    if (lists.length > 0) {
        ctx.body = {
            code: 1000,
            data: lists
        }
    } else {
        ctx.body = {
            code: 400,
            data: ''
        }
    }
}

let fn_add = async (ctx, next) => {
    let obj = ctx.request.body
    if (obj.biaoti != '' && obj.zhaiyao != '') {
        await User.create({
            biaoti: obj.biaoti,
            zhaiyao: obj.zhaiyao,
            neirong: obj.neirong,
            fenlei: obj.fenlei,
            zuozhe: obj.zuozhe
        })
        ctx.body = 1000
    } else {
        ctx.body = 400
    }
}

let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id
    if (id != '') {
        await User.destroy({
            where: {
                id: id
            }
        })
    }
    ctx.body = 1
}

let fn_put = async (ctx, next) => {
    let obj = ctx.request.body
    await User.update({ biaoti: obj.biaoti, zhaiyao: obj.zhaiyao, neirong: obj.neirong, fenlei: obj.fenlei, zuozhe: obj.zuozhe }, {
        where: {
            id: obj.id
        }
    })
    ctx.body = 1
}

module.exports = {
    'get /user': fn_user,
    'get /user/:word': fn_cha,
    'post /user': fn_add,
    'delete /user/:id': fn_delete,
    'put /user': fn_put
}